package edu.suda.xsap.controller;

import edu.suda.xsap.dto.CaptchaVerificationRequest;
import edu.suda.xsap.dto.LoginRequest;
import edu.suda.xsap.service.RegisterService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@RestController
@RequestMapping("/verify")
public class CaptchaVerificationController {
    @Autowired
    private RegisterService registerService;

    private static final Logger log = LoggerFactory.getLogger(CaptchaVerificationController.class);
    @PostMapping("/code")
    public boolean verifyCaptcha(HttpServletRequest request,
                                 @RequestBody CaptchaVerificationRequest captchaRequest) {

        String userInputCaptcha = captchaRequest.getCaptcha();
        String storedCaptcha = (String) request.getSession().getAttribute("verifyCode");
        log.info("Received captcha: {}", userInputCaptcha);
        log.info("Stored captcha: {}", storedCaptcha);
        if (storedCaptcha != null && storedCaptcha.equalsIgnoreCase(userInputCaptcha)) {
            // 验证成功，清除 Session 中的验证码
            request.getSession().removeAttribute("verifyCode");
            return true;
        }
        return false;
    }

    @PostMapping("/login")
    public boolean login(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        log.info("Received login request: username={}, password={}", username, password);
        // 验证用户名和密码
        if (username.equals("admin") && password.equals("password")) {
            // 验证成功，设置 Session 属性
            request.getSession().setAttribute("username", username);
            return true;
        }else{
            //获取注册表内的信息判断用户名和密码是否匹配
            if(registerService.findByName(username).getPassword().equals(password)){
                request.getSession().setAttribute("username", username);
                return true;
            }
        }
        return false;
    }
}
